class SelectionTranslator {
    constructor() {
        this.bubble = null;
        this.isEnabled = true;
        this.currentAPI = 'libre';
        this.targetLanguage = 'zh';
        this.loadSettings();
        this.setupEventListeners();
    }

    // 加载设置
    loadSettings() {
        chrome.storage.sync.get(['targetLanguage', 'translationApi', 'enableSelection'], (result) => {
            this.targetLanguage = result.targetLanguage || 'zh';
            this.currentAPI = result.translationApi || 'libre';
            this.isEnabled = result.enableSelection !== false;
        });
    }

    // 设置事件监听
    setupEventListeners() {
        document.addEventListener('mouseup', this.handleMouseUp.bind(this));
        document.addEventListener('mousedown', this.handleMouseDown.bind(this));
        
        // 监听来自popup的消息
        chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
            if (request.action === 'toggleSelection') {
                this.isEnabled = !this.isEnabled;
                if (!this.isEnabled && this.bubble) {
                    this.removeBubble();
                }
            }
        });
    }

    // 处理鼠标抬起事件
    handleMouseUp(event) {
        if (!this.isEnabled) return;

        const selection = window.getSelection();
        const selectedText = selection.toString().trim();

        if (selectedText && !this.isClickInBubble(event)) {
            this.handleTextSelection(selectedText, event);
        }
    }

    // 处理鼠标按下事件
    handleMouseDown(event) {
        if (this.bubble && !this.isClickInBubble(event)) {
            this.removeBubble();
        }
    }

    // 检查点击是否在气泡内
    isClickInBubble(event) {
        return this.bubble && this.bubble.contains(event.target);
    }

    // 处理选中文本
    async handleTextSelection(text, event) {
        if (this.bubble) {
            this.removeBubble();
        }

        this.createBubble(event);
        this.showLoading();

        try {
            const translation = await this.translate(text);
            this.updateBubbleContent(text, translation);
        } catch (error) {
            this.showError(error.message);
        }
    }

    // 创建翻译气泡
    createBubble(event) {
        this.bubble = document.createElement('div');
        this.bubble.className = 'translation-bubble';
        
        // 计算气泡位置
        const rect = window.getSelection().getRangeAt(0).getBoundingClientRect();
        const bubbleHeight = 150; // 预估高度
        const spaceBelow = window.innerHeight - (rect.bottom + window.pageYOffset);
        
        // 决定气泡显示在选中文本的上方还是下方
        if (spaceBelow < bubbleHeight && rect.top > bubbleHeight) {
            this.bubble.style.top = (rect.top + window.pageYOffset - bubbleHeight - 10) + 'px';
            this.bubble.classList.add('bottom');
        } else {
            this.bubble.style.top = (rect.bottom + window.pageYOffset + 10) + 'px';
        }
        
        this.bubble.style.left = (rect.left + window.pageXOffset) + 'px';
        document.body.appendChild(this.bubble);
    }

    // 显示加载状态
    showLoading() {
        this.bubble.innerHTML = '<div class="translation-loading"></div>';
    }

    // 更新气泡内容
    updateBubbleContent(originalText, translatedText) {
        this.bubble.innerHTML = `
            <div class="translation-bubble-header">
                <span class="translation-bubble-title">翻译结果</span>
                <span class="translation-bubble-close" title="关闭">✕</span>
            </div>
            <div class="translation-bubble-content">
                <div class="original-text">${originalText}</div>
                <div class="translated-text">${translatedText}</div>
            </div>
            <div class="translation-bubble-footer">
                <button class="translation-bubble-button" title="朗读">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/>
                    </svg>
                </button>
                <button class="translation-bubble-button" title="复制">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
                    </svg>
                </button>
            </div>
        `;

        // 添加事件监听
        this.bubble.querySelector('.translation-bubble-close').addEventListener('click', () => this.removeBubble());
        
        // 复制按钮
        this.bubble.querySelector('.translation-bubble-button[title="复制"]').addEventListener('click', () => {
            navigator.clipboard.writeText(translatedText);
        });

        // 朗读按钮
        this.bubble.querySelector('.translation-bubble-button[title="朗读"]').addEventListener('click', () => {
            const utterance = new SpeechSynthesisUtterance(translatedText);
            utterance.lang = this.targetLanguage;
            window.speechSynthesis.speak(utterance);
        });
    }

    // 显示错误信息
    showError(message) {
        this.bubble.innerHTML = `
            <div class="translation-bubble-header">
                <span class="translation-bubble-title">错误</span>
                <span class="translation-bubble-close" title="关闭">✕</span>
            </div>
            <div class="translation-bubble-content">
                <div class="translated-text" style="color: #dc3545;">${message}</div>
            </div>
        `;

        this.bubble.querySelector('.translation-bubble-close').addEventListener('click', () => this.removeBubble());
    }

    // 移除气泡
    removeBubble() {
        if (this.bubble && this.bubble.parentNode) {
            this.bubble.parentNode.removeChild(this.bubble);
            this.bubble = null;
        }
    }

    // 翻译文本
    async translate(text) {
        return new Promise((resolve, reject) => {
            chrome.runtime.sendMessage({
                action: 'translate',
                text: text,
                targetLanguage: this.targetLanguage,
                api: this.currentAPI
            }, response => {
                if (response.error) {
                    reject(new Error(response.error));
                } else {
                    resolve(response);
                }
            });
        });
    }
}

// 初始化划词翻译
const selectionTranslator = new SelectionTranslator();
